package com.good.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {

	public static void main(String[] args) throws ClientProtocolException,
			IOException {
		tPost();
	}

	public static void tPost() {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost("http://www.baidu.com");

		// 创建参数队列
		List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
		formparams.add(new BasicNameValuePair("type", "house"));
		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); // url转码
			httpPost.setEntity(uefEntity);
			CloseableHttpResponse httpResponse=httpClient.execute(httpPost);
			System.out.println(httpResponse.getStatusLine());
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				httpClient.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static void tGet() throws ClientProtocolException, IOException {
		HttpGet httpGet = new HttpGet("http://www.baidu.com");// 创建一个http get请求
		System.out.println("获取请求行" + httpGet.getRequestLine());
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse httpResponse = httpClient.execute(httpGet);// 执行http请求
		System.out.println("HttpResponse===" + httpResponse);
		String str = EntityUtils.toString(httpResponse.getEntity(),
				Charset.forName("utf-8"));
		System.out.println("获取响应体====" + str);
		System.out.println("获取状态码===" + httpResponse.getStatusLine());
		Header[] headers = httpResponse.getAllHeaders();// 获取所有的http头对象
		for (Header header : headers) {
			System.out.println("key:" + header.getName() + "===" + "value:"
					+ header.getValue());

		}
		httpResponse.close();
		httpClient.close();
	}

}
